package org.smartjava.core.juc.atomic;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class AtomicReferenceScore {
    private static Score highScore = new Score("nobody", 0);

    public static void main(String[] args) {
        validate();
    }

    private static void validate() {
        for (int i = 0; i < 1000; i++) {
            final Score[] high = {new Score("nobody", 0)};
            int num = 1000;
            List<Score> scoreList = generateScore(num);
            CountDownLatch countDownLatch = new CountDownLatch(num);
            scoreList.forEach(score -> new Thread(() -> {
                if (high[0].score < score.score) {
                    high[0] = score;
                }
                countDownLatch.countDown();
            }).start());
            await(countDownLatch);
            if (high[0].score != 2000) {
                System.out.println(highScore);
                break;
            }
        }

    }

    private static void await(CountDownLatch countDownLatch) {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static List<Score> generateScore(int num) {
        List<Score> scoreList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            scoreList.add(new Score("Score" + i, i));
        }
        scoreList.get(100).score = 2000;
        return scoreList;
    }


}

class Score {
    public String name;
    public int score;

    public Score(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Score{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}
